package cn.hesion.dataStructures.Search;

public class BinarySearch {
    public static void main(String[] args) {
        //二分查找的数组是有序的。
        int[] arr = {1, 8, 10, 89, 1000, 1234};
        int index = binarySearch(arr, 0, arr.length-1, 1234);
        if (index != -1) {
            System.out.println("你要查找的数的数组下标为:" + index);
        }
    }

    public static int binarySearch(int[] arr, int left, int right, int findVal) {
        int mid = (left + right) / 2;
        int midVal = arr[mid];
        //递归结束条件
        if (left > right) {
            System.out.println("你要查找的值：" + findVal + ",不在该数组中");
            return -1;
        }
        if (findVal > midVal) {
            return binarySearch(arr, mid + 1, right, findVal);
        } else if (findVal < midVal) {
            return binarySearch(arr, left, mid - 1, findVal);
        } else {
            return mid;
        }
    }
}
